package com.lzc.springcloud.zuul.config.properties;


import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;

public class PermitURLProperties {
    private static List<Pattern> urlPatterns;
    private List<url> urls;

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @PostConstruct
    public void init() {
        if (urls != null && urls.size() > 0) {
            this.urlPatterns = new ArrayList();
            Iterator<url> iterator = urls.iterator();
            while (iterator.hasNext()) {
                String currentUrl = iterator.next().getPattern().replaceAll("\\*\\*", "(.*?)");
                Pattern currentPattern = Pattern.compile(currentUrl, Pattern.CASE_INSENSITIVE);
                urlPatterns.add(currentPattern);
            }

        }
    }

    public String[] getPermitUrlPatterns() {
        List<String> urlStrs = new ArrayList();
        Iterator<url> iterator = urls.iterator();
        while (iterator.hasNext()) {
            urlStrs.add(iterator.next().getPattern());
        }
        return urlStrs.toArray(new String[0]);
    }

    public static class url {
        private String pattern;

        public String getPattern() {
            return pattern;
        }

        public void setPattern(String pattern) {
            this.pattern = pattern;
        }
    }

    public boolean isPermitAllUrl(String url) {
        for (Pattern pattern : urlPatterns) {
            if (pattern.matcher(url).find()) {
                return true;
            }
        }
        return false;
    }

    public static List<Pattern> getUrlPatterns() {
        return urlPatterns;
    }

    public static void setUrlPatterns(List<Pattern> urlPatterns) {
        PermitURLProperties.urlPatterns = urlPatterns;
    }

    public List<url> getUrls() {
        return urls;
    }

    public void setUrls(List<url> urls) {
        this.urls = urls;
    }
}
